package com.ellfors.common.base.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter4.BaseDifferAdapter

/**
 * 只有一种类型且需要DiffUtils的Adapter
 *
 * @property diffCallback DiffUtil
 */
abstract class BaseDiffAdapter<T : Any, VB : ViewBinding>(
    private val diffCallback: DiffUtil.ItemCallback<T>
) : BaseDifferAdapter<T, BaseDiffAdapter.DiffViewHolder<VB>>(diffCallback) {

    class DiffViewHolder<VB : ViewBinding>(val binding: VB) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(
        context: Context, parent: ViewGroup, viewType: Int
    ): DiffViewHolder<VB> {
        return DiffViewHolder(initViewBinding(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: DiffViewHolder<VB>, position: Int, item: T?) {
        convert(holder, position, item)
    }

    override fun onBindViewHolder(
        holder: DiffViewHolder<VB>, position: Int, item: T?, payloads: List<Any>
    ) {
        if (payloads.isNotEmpty()) {
            convertByPayloads(holder, position, item, payloads)
        } else {
            super.onBindViewHolder(holder, position, item, payloads)
        }
    }

    override fun isFullSpanItem(itemType: Int): Boolean {
        return true
    }

    /**
     * example: ItemMainBinding::inflate
     */
    abstract val initViewBinding: (LayoutInflater, ViewGroup, Boolean) -> VB

    /**
     * 渲染ViewHolder
     */
    abstract fun convert(holder: DiffViewHolder<VB>, position: Int, item: T?)

    /**
     * 差异化更新
     */
    open fun convertByPayloads(
        holder: DiffViewHolder<VB>, position: Int, item: T?, payloads: List<Any>
    ) {

    }
}